//
//  XTabBarViewController.swift
//  WeiBoReDo
//
//  Created by 放学跟鸽走 on 2017/4/8.
//  Copyright © 2017年 放学跟鸽走. All rights reserved.
//

import UIKit
import SVProgressHUD
/// 主控制器
class XMainController: UITabBarController{
    
    
    fileprivate var timer:Timer?
    
    var badgeNum:Int = 0{
        didSet{
            setBadgNum(count: badgeNum)
        }
    }
    /// 加号按钮
    fileprivate lazy var composedButton: UIButton = UIButton.cz_imageButton("tabbar_compose_icon_add", backgroundImageName: "tabbar_compose_button")

    override func viewDidLoad() {
        super.viewDidLoad()
        delegate = self
        //添加子控制器
        addChildControllers()
        //设置加号按钮
        setupComposedButton()
        //定时器设置
//        setupTimer()
        //注册登录通知
        NotificationCenter.default.addObserver(self, selector: #selector(login), name: NSNotification.Name.init(rawValue: XUserShouldLoginNotification), object: nil)
        
    }
    deinit {
        //时钟销毁
        timer?.invalidate()
        //注销登录通知
        NotificationCenter.default.removeObserver(self)
    }
    func login(n:Notification){
        var when  = DispatchTime.now()
        if n.object != nil{
            // 设置指示器渐变样式
            SVProgressHUD.setDefaultMaskType(.gradient)
            
            SVProgressHUD.showInfo(withStatus: "用户登录已经超时，需要重新登录")
            SVProgressHUD.setDefaultMaskType(.clear)
            
            when = DispatchTime.now() + 3
        }
        DispatchQueue.main.asyncAfter(deadline:when) {
            
            let nav = UINavigationController(rootViewController: XOauthViewController())
            self.present(nav, animated: true, completion: nil)
        }
    }
    /// 加号按钮点击事件
    func compose(){
        print(#function)
    }
    //使用代码控制设备的方向，可以在需要横屏的时候，单独处理
    //设置支持的方向后，当前的控制器控制器及子控制器都会遵守这个方向
    //在这里设置全局竖屏，不影响modal出的控制器，即modal出的控制器可以自己设置横屏
    override internal var supportedInterfaceOrientations: UIInterfaceOrientationMask{
        return .portrait
    }

}
// MARK: - 获取未读微博数量
fileprivate extension XMainController{
    
    /// 定时器设置
    func setupTimer() {
        timer = Timer.scheduledTimer(timeInterval: 60, target: self, selector: #selector(getUnReadCount), userInfo: nil, repeats: true)
        
        
        
    }
    @objc func getUnReadCount(){
//        print("定时获取未读微博数量")
        if XNetworkManager.shared.isLogin{
            XNetworkManager.shared.unReadStatusCount(complete: { (count) in
                self.badgeNum = count
            })
        }
    }
    /// 方法描述：设置tabBar上的数字以及APP图标上的数字
     func setBadgNum(count:Int){
        tabBar.items?[0].badgeValue = count>0 ? "\(count)":nil
        //ios8后需要授权才能在图标上显示数字
        UIApplication.shared.applicationIconBadgeNumber = count
    }
}
fileprivate extension XMainController{
    /// 设置撰写按钮
     func setupComposedButton() {
        tabBar.addSubview(composedButton)
        
        let count = childViewControllers.count
        let w = tabBar.bounds.width / CGFloat(count)
//        let h = tabBar.bounds.height
        
        composedButton.frame = tabBar.bounds.insetBy(dx: 2*w, dy: 0)
        
        composedButton.addTarget(self, action: #selector(compose), for: .touchUpInside)
    }

}
// MARK: - 添加子控制器
fileprivate extension XMainController{
    /// 方法描述：
     func addChildControllers(){
        //1.获取main.json的path
        guard let path:String = Bundle.main.path(forResource: "main.json", ofType: nil),
        let data = try? Data(contentsOf: URL(fileURLWithPath: path)),
            let jsonArray = try? (JSONSerialization.jsonObject(with: data, options: []) as? [[String:Any]]) ?? []

            else{
                return
        }
          //得到data
        //转化为字典数组
        //遍历数组
        var arrayCtrs:[XNavigationController] = [XNavigationController]()
        for dict in jsonArray{
            //添加子控制器
            let vc = initChildController(dict: dict)
           
             arrayCtrs.append(vc)
            
            
        }
        viewControllers = arrayCtrs
        
    }
    /// 方法描述：字典转模型，返回一个导航控制器
    private func initChildController(dict:[String:Any]) -> XNavigationController{
        
        guard let clsName = dict["clsName"] as? String,
        let imageName = dict["imageName"] as? String,
        let title = dict["title"] as? String,
        let visitorInfo = dict["visitorInfo"] as? [String:String],
        let cls = NSClassFromString(Bundle.main.namespace+"."+clsName) as? XBaseController.Type
        else{
            
            return  XNavigationController()
        }
        
        let vc = cls.init()
        vc.title = title
        let imageStr = "tabbar_"+imageName
        vc.tabBarItem = UITabBarItem(title: title, image: UIImage(named: imageStr), selectedImage: UIImage(named: imageStr+"_selected")?.withRenderingMode(.alwaysOriginal))
        
        vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.orange], for: .selected)
        vc.visitorInfo = visitorInfo
        vc.tabBarItem.setTitleTextAttributes([NSFontAttributeName:UIFont.systemFont(ofSize: 12)], for: .normal)
//        vc.tabBarItem.image = UIImage(named: "tabbar_"+imageName)
//        
//        vc.tabBarItem.selectedImage = UIImage(named: "tabbar_"+imageName+"_highlighted")?.withRenderingMode(.alwaysOriginal)
        
        return XNavigationController(rootViewController: vc)

    }
    
}
extension XMainController:UITabBarControllerDelegate{
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
         let count = viewController.childViewControllers.count
        //是加号按钮，不处理其点击事件
        if(count == 0) {
            return false
        }
        let index = childViewControllers.index(of: viewController) ?? 0
        print("即将选中\(index) --目前为\(selectedIndex)")
//        print(vc.childViewControllers.count)
        if index==0 && index == selectedIndex && badgeNum != 0{
            print("已经是首页了，再次点击了首页，准备刷新")
            guard let vc = viewController.childViewControllers[0] as? XHomeViewController
                else{
                    return true
            }
            vc.myTableView?.setContentOffset(CGPoint(x: 0, y: -64), animated: true)
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1, execute: {[weak self] in
                
                vc.loadData()
                self?.badgeNum = 0
            })
        }
        return true
        
    }
}
